const pool = require('../config/database');

class FamilyBedHistoryModel {
  /**
   * 创建家庭病床史记录
   * @param {Object} bedData - 家庭病床史数据
   * @returns {Promise<Object>} 创建的家庭病床史记录
   */
  static async create(bedData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const fields = Object.keys(bedData);
      const values = Object.values(bedData);
      const placeholders = fields.map(() => '?').join(', ');
      
      const sql = `
        INSERT INTO jktj_family_bed_history (${fields.join(', ')})
        VALUES (${placeholders})
      `;
      
      const [result] = await connection.execute(sql, values);
      
      await connection.commit();
      
      return {
        id: result.insertId,
        ...bedData
      };
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 批量创建家庭病床史记录
   * @param {Array<Object>} bedList - 家庭病床史数据数组
   * @returns {Promise<Array>} 创建的家庭病床史记录数组
   */
  static async createBatch(bedList) {
    if (!bedList || bedList.length === 0) {
      return [];
    }

    const connection = await pool.getConnection();
    const results = [];
    
    try {
      await connection.beginTransaction();
      
      for (const bedData of bedList) {
        const fields = Object.keys(bedData);
        const values = Object.values(bedData);
        const placeholders = fields.map(() => '?').join(', ');
        
        const sql = `
          INSERT INTO jktj_family_bed_history (${fields.join(', ')})
          VALUES (${placeholders})
        `;
        
        const [result] = await connection.execute(sql, values);
        
        results.push({
          id: result.insertId,
          ...bedData
        });
      }
      
      await connection.commit();
      return results;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 根据体检ID获取家庭病床史记录列表
   * @param {number} tjId - 体检ID
   * @returns {Promise<Array>} 家庭病床史记录列表
   */
  static async findByTjId(tjId) {
    const sql = 'SELECT * FROM jktj_family_bed_history WHERE tj_id = ? ORDER BY ryrq DESC';
    const [rows] = await pool.execute(sql, [tjId]);
    return rows;
  }

  /**
   * 根据ID获取家庭病床史记录
   * @param {number} id - 家庭病床史记录ID
   * @returns {Promise<Object>} 家庭病床史记录
   */
  static async findById(id) {
    const sql = 'SELECT * FROM jktj_family_bed_history WHERE id = ?';
    const [rows] = await pool.execute(sql, [id]);
    return rows[0] || null;
  }

  /**
   * 更新家庭病床史记录
   * @param {number} id - 家庭病床史记录ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<boolean>} 更新结果
   */
  static async update(id, updateData) {
    const fields = Object.keys(updateData);
    const values = Object.values(updateData);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    const sql = `UPDATE jktj_family_bed_history SET ${setClause} WHERE id = ?`;
    const [result] = await pool.execute(sql, [...values, id]);
    
    return result.affectedRows > 0;
  }

  /**
   * 删除家庭病床史记录
   * @param {number} id - 家庭病床史记录ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async delete(id) {
    const sql = 'DELETE FROM jktj_family_bed_history WHERE id = ?';
    const [result] = await pool.execute(sql, [id]);
    return result.affectedRows > 0;
  }

  /**
   * 根据体检ID删除所有家庭病床史记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async deleteByTjId(tjId) {
    const sql = 'DELETE FROM jktj_family_bed_history WHERE tj_id = ?';
    const [result] = await pool.execute(sql, [tjId]);
    return result.affectedRows > 0;
  }

  /**
   * 批量获取多个体检的家庭病床史记录
   * @param {Array<number>} tjIds - 体检ID数组
   * @returns {Promise<Array>} 家庭病床史记录数组
   */
  static async findByTjIds(tjIds) {
    if (!tjIds || tjIds.length === 0) {
      return [];
    }
    
    const placeholders = tjIds.map(() => '?').join(', ');
    const sql = `
      SELECT * FROM jktj_family_bed_history 
      WHERE tj_id IN (${placeholders}) 
      ORDER BY tj_id, ryrq DESC
    `;
    const [rows] = await pool.execute(sql, tjIds);
    return rows;
  }

  /**
   * 获取指定时间范围内的家庭病床史记录
   * @param {number} tjId - 体检ID
   * @param {Date} startDate - 开始日期
   * @param {Date} endDate - 结束日期
   * @returns {Promise<Array>} 家庭病床史记录列表
   */
  static async findByDateRange(tjId, startDate, endDate) {
    const sql = `
      SELECT * FROM jktj_family_bed_history 
      WHERE tj_id = ? AND ryrq >= ? AND ryrq <= ?
      ORDER BY ryrq DESC
    `;
    const [rows] = await pool.execute(sql, [tjId, startDate, endDate]);
    return rows;
  }

  /**
   * 计算家庭病床使用天数
   * @param {Object} bedData - 家庭病床史数据
   * @returns {number} 使用天数
   */
  static calculateBedDays(bedData) {
    if (!bedData.ryrq || !bedData.cyrq) {
      return 0;
    }
    
    const startDate = new Date(bedData.ryrq);
    const endDate = new Date(bedData.cyrq);
    const timeDiff = endDate.getTime() - startDate.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
    
    return daysDiff > 0 ? daysDiff : 0;
  }
}

module.exports = FamilyBedHistoryModel;